package com.capinfo.commons.project.web.controller.manage.region;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;

import com.capinfo.commons.project.model.region.Region;
import com.capinfo.commons.project.model.security.SystemResource;
import com.capinfo.commons.project.parameter.region.RegionParameter;
import com.capinfo.commons.project.parameter.security.SystemResourceParameter;
import com.capinfo.commons.project.service.region.RegionService;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.dwr.fetch.FetchRegion;
import com.capinfo.framework.web.util.WebRequestUtils;



/**
 * 作成日期： 2014-1-20 
 * <p>功能描述:  区域管理</p>
 * @author  xuxianping
 * @version 0.1
 */
@Controller
@RequestMapping("/manage/region")
public class RegionManageController extends CommonsDataManageController<RegionParameter, Region>{
	private static final Log logger = LogFactory.getLog(RegionManageController.class);
	
	@Autowired
	private RegionService regionService;
	
	
	/**
	 * <p>描述: 初始化页面</p>
	 * @param request
	 * @param parameter
	 * @return
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/initial.shtml")
	public Map<String, Object> initial(NativeWebRequest request, RegionParameter parameter) {

		Map<String, Object> viewModel = new HashMap<String, Object>();
		
		return viewModel;
	}
	
	/**
	 * <p>描述: 获得区域下一级</p>
	 * @param request
	 * @param parameter 
	 * @param stream
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/getRegion.shtml")
	public void getRegion(NativeWebRequest request, RegionParameter parameter, OutputStream stream){
		WebRequestUtils.setCharacterEncodingForUTF8(request);
		WebRequestUtils.setContentTypeForHTML(request);
		
		if(null != parameter.getEntity().getId()){
			
			Region region = regionService.getRegionById(parameter.getEntity().getId());
			JSONObject json = new JSONObject();
			json.put("id", region.getId());
			json.put("name", region.getName());
			json.put("parentId", region.getParentId());
			try {
				IOUtils.outputByStream(stream , json.toString().getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				LogUtils.debugException(logger, e);
			}
		}
	}
	
	
	/**
	 * <p>描述: 获得指定区域的id（包含上级）</p>
	 * @param request
	 * @param parameter 
	 * @param stream
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/getSpecifiedIds.shtml")
	public void getSpecifiedIds(NativeWebRequest request, RegionParameter parameter, OutputStream stream){
		WebRequestUtils.setCharacterEncodingForUTF8(request);
		WebRequestUtils.setContentTypeForHTML(request);
		
		if(null != parameter.getEntity().getId()){
			
			String specifiedIds = regionService.getRegionIds(parameter.getEntity().getId());
			try {
				IOUtils.outputByStream(stream , specifiedIds.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				LogUtils.debugException(logger, e);
			}
		}
	}
	
	
	/**
	 * <p>描述: 获得区域下一级</p>
	 * @param request
	 * @param parameter 
	 * @param stream
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/getChildren.shtml")
	public void getChildren(NativeWebRequest request, RegionParameter parameter, OutputStream stream){
		WebRequestUtils.setCharacterEncodingForUTF8(request);
		WebRequestUtils.setContentTypeForHTML(request);
		
		if(null != parameter.getEntity().getId()){
			
			String children = regionService.getChildrenJson(parameter.getEntity().getId());
			if(StringUtils.isNotBlank(children)){
				
				try {
					IOUtils.outputByStream(stream, children.getBytes("UTF-8"));
				} catch (UnsupportedEncodingException e) {
					LogUtils.debugException(logger, e);
				}
			}
		}
	}
	
	
	/**
	 * <p>描述: 新增或修改区域，返回新增或修改的区域JSON</p>
	 * @param request
	 * @param parameter
	 * @param stream
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/saveOrUpdate.shtml")
	public void saveOrUpdate(NativeWebRequest request, RegionParameter parameter, OutputStream stream) {

		Region region = regionService.saveOrUpdate(parameter);
		JSONObject json = new JSONObject();
		
		try {
			if(null != region){
			
				json.put("id", region.getId());
				json.put("name", region.getName());
			}
			IOUtils.outputByStream(stream , json.toString().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			LogUtils.debugException(logger, e);
		}
	}
	
	
	/**
	 * <p>描述: 获取区域数据， 返回JSON</p>
	 * @param request
	 * @param parameter
	 * @param stream
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("/regionJson.shtml")
	public void regionJson(NativeWebRequest request, OutputStream stream) {

		WebRequestUtils.setCharacterEncodingForUTF8(request);
		WebRequestUtils.setContentTypeForHTML(request);
		
		try {
			IOUtils.outputByStream(stream , regionService.getRegionJson().getBytes("UTF-8"));
		} catch (Exception e) {
			LogUtils.debugException(logger, e);
		}
	}
	
	
	/**
	 * <p>描述: 生成区域缓存，将生成的数据存入数据库，使查询区域数据时不用每次都查询数据库以及生产JSON而影响性能</p>
	 * @param request
	 * @param parameter
	 * @param writer
	 * @author: xuxianping
	 * @update:
	 */
	@RequestMapping("build.shtml")
	public void build(NativeWebRequest request, RegionParameter parameter, Writer writer) {
		
		boolean token = regionService.buildRegionJson(parameter);
		IOUtils.outputByWriter(writer, token);
	}
	
	
	@Override
	public CommonsDataOperationService<Region, RegionParameter> getCommonsDataOperationService() {
		return regionService;
	}
	
	
}
